package rpcx

import (
	"gogame/lib"
	"gogame/pb"
	"google.golang.org/protobuf/proto"
	"sync"
)

/*对pb.ApiResponse进行的二次封装*/

type Response struct {
	pb.ApiResponse
}

func NewResponse(apiResponse pb.ApiResponse) *Response {
	_response := ResponsePool.Get()
	_response.ApiResponse = apiResponse

	return _response
}

// Reset 资源重置
func (r *Response) Reset() {
	r.ApiResponse.S = 0
	r.ApiResponse.ErrorMsg = ""
	r.ApiResponse.ResponseApi = ""
	r.ApiResponse.Data = nil
	r.ApiResponse.StringMsg = nil
	r.ApiResponse.Uid = "nil"
	r.ApiResponse.FirstResponse = nil
	r.ApiResponse.IsCheck = 0
}

// SendMsg 接口响应
func (r *Response) SendMsg(msg proto.Message) {
	r.Data = lib.NewProtoAny(msg)

}

// SendFirstProtoMsg 接口中提前返回的pb消息
func (r *Response) SendFirstProtoMsg(key string, data proto.Message) {
	r.FirstResponse = append(
		r.FirstResponse,
		&pb.Response{
			ResponseApi: key,
			Data:        lib.NewProtoAny(data),
		},
	)

}

// SendFirstJson 接口中提前返回的json消息
func (r *Response) SendFirstJson(data any) {
	r.FirstResponse = append(
		r.FirstResponse,
		&pb.Response{
			StringMsg: lib.Dumps(data),
		},
	)

}

/*
 ---------- pool 减少GC ----------
*/
type responsePool struct {
	pool *sync.Pool
}

var ResponsePool = &responsePool{
	pool: &sync.Pool{
		New: func() any {
			return &Response{}
		},
	},
}

func (p *responsePool) Get() *Response {
	return p.pool.Get().(*Response)
}

func (p *responsePool) Put(response *Response) {
	response.Reset()
	p.pool.Put(response)
}

// PutResponse 资源回收
func PutResponse(response *Response) {
	ResponsePool.Put(response)
}
